<template>
	<view>
		<view class="search-box">
			<uni-search-bar :radius="100" placeholder="请输入搜索内容" cancelButton="none" clearButton="auto" @input="input"></uni-search-bar>
		</view>
		
		<!-- 搜索建议列表 -->
		<view class="sugg-list" v-if="searchResults.length != 0">
			<view class="sugg-item" v-for="(item, idx) in searchResults" :key="idx" @click="gotoDetail(item)">
				<view class="goods-name">
					{{item.goods_name}}
				</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
		
		<!-- 搜索历史 -->
		<view class="history-box" v-else>
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="17" @click="clean"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag :text="item" v-for="(item,idx) in historyList" :key="idx" @click="gotoGoodsList(item)"></uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer: null,
				kw: "",
				//搜索结果列表
				searchResults: [],
				//搜索历史数组
				historyList: JSON.parse(uni.getStorageSync("kw") || "[]")
			};
		},
		onLoad() {
			
		},
		conputed() {
			
		},
		methods: {
			gotoGoodsList(item) {
				uni.navigateTo({
					url: "/subpkg/goods_detail/goods_detail?query=" + item
				})
			},
			clean() {
				this.historyList = []
				uni.setStorageSync("kw", "[]")
			},
			//保存搜索历史记录
			saveSearchHistory() {
				if(this.historyList.every(item => {return this.kw != item})) {
					this.historyList.unshift(this.kw)
				}
				//对搜索历史数据进行持久化存储
				uni.setStorageSync("kw", JSON.stringify(this.historyList))
			},
			gotoDetail(item) {
				uni.navigateTo({
					url:"/subpkg/goods_detail/goods_detail?query=" + item.goods_id
				})
			},
			input(event) {
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.kw = event
					this.getSearchList()
				}, 500)
			},
			async getSearchList() {
				if(this.kw == "") {
					this.searchResults = []
					return
				}
				const res = await uni.$http.get("/api/public/v1/goods/qsearch", {query: this.kw})
				if(res.data.meta.status == 200) {
					this.searchResults = res.data.message
					this.saveSearchHistory()
				} else {
					return uni.$showMsg()
				}
			}
		}
	}
</script>

<style lang="scss">
.search-box {
	position: sticky;
	top: 0;
	z-index: 999;
}
.sugg-list {
	padding: 0 5px;
	.sugg-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 12px;
		padding: 13px 0;
		border-bottom: 1px solid #CCC;
		.goods-name {
			//文字不允许换行
			white-space: nowrap;
			//超出部分隐藏
			overflow: hidden;
			//文本溢出后,用...代替
			text-overflow: ellipsis;
		}
	}
}
.history-box {
	padding: 0 5px;
	.history-title {
		height: 40px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 13px;
		border-bottom: 1px solid #efefef;
	}
	.history-list {
		display: flex;
		flex-wrap: wrap;
		.uni-tag {
			background-color: #ccc;
			border: none;
			color: #000;
			margin: 5px 5px 0 0;
		}
	}
}
</style>
